package com.uusee.crawler.pageprocessor.video.ku6;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.uusee.crawler.framework.Processor;
import com.uusee.crawler.model.CrawlStatusCodes;
import com.uusee.crawler.model.CrawlURI;
import com.uusee.crawler.util.DomainUtils;
import com.uusee.crawler.util.PageProcessorUtils;
import com.uusee.shipshape.sp.model.Ugc;
import com.uusee.util.StringUtils;
import com.uusee.util.date.DateUtil;

public class Ku6UserVideoInterfacePageProcessor extends Processor {
	private Log log = LogFactory.getLog(Ku6UserVideoInterfacePageProcessor.class);
	private Map<String,String> channelMap;
	
	{
		channelMap = new HashMap<String,String>();
		channelMap.put("105000", "原创");
		channelMap.put("104000", "电影");
		channelMap.put("117000", "电视剧");
		channelMap.put("110000", "动漫");	
		channelMap.put("116000", "音乐");
		channelMap.put("108000", "搞笑");
		channelMap.put("101000", "资讯");
		channelMap.put("103000", "娱乐");
		channelMap.put("102000", "体育");
		channelMap.put("119000", "拍客");
		channelMap.put("109000", "游戏");
		channelMap.put("112000", "文化");
		channelMap.put("121000", "时尚");
		channelMap.put("106000", "广告");
		channelMap.put("114000", "汽车");
		channelMap.put("122000", "健康");
		channelMap.put("123000", "母婴");
		channelMap.put("113000", "生活");
		channelMap.put("111000", "教育");
		channelMap.put("115000", "房产");
		channelMap.put("118000", "综艺");
		channelMap.put("125000", "我是女生");
	}
	
	public void innerProcess(CrawlURI crawlURI) {
		if (!canProcess(crawlURI)) {
			return;
		}
		Date crawlDate = new Date();
		String crawlUser = "uusee-crawler";
		String videoSite = crawlURI.getSourceSite();
		String crawlUrl = crawlURI.getCrawlUrl();
		String crawlResult = crawlURI.getCrawlResult();
		
		List<CrawlURI> playCrawlURIList = (List<CrawlURI>)crawlURI.getModel();
		if (playCrawlURIList==null) {
			playCrawlURIList = new ArrayList<CrawlURI>();
			crawlURI.setModel(playCrawlURIList);
		}
		 
		try {
			JSONObject jsonObject = JSONObject.fromObject( crawlResult ); 
			JSONArray items = new JSONArray();
			if (jsonObject.containsKey("data")) {
				JSONObject dataObject = jsonObject.getJSONObject("data");
				items = dataObject.getJSONArray("list");
			}
			if (items.size()==0) {
				crawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_INVALID);
				return;
			}
			
			Iterator it = items.iterator();
			while(it.hasNext()){
				JSONObject item = (JSONObject)it.next();
				String evid = item.getString("vid");
				String playUrl = "http://v.ku6.com/show/"+evid+".html";
				String shareUrl = "http://player.ku6.com/refer/"+evid+"/v.swf";
				String playSite = PageProcessorUtils.getValue("http://([^/]*?)/", playUrl);
				String domain = DomainUtils.getDomain(playUrl);
				String title = PageProcessorUtils.unicodeToChinese(item.getString("title"));
				String logo = PageProcessorUtils.unicodeToChinese(item.getString("picPath"));
				if (!logo.startsWith("http://")) {
					logo = "http://"+logo;
				}
				//String cusCoverUrl = "";
				//if (item.containsKey("cusCoverUrl")) {
				//    cusCoverUrl = item.getString("cusCoverUrl");
			    //}
				int length = item.getInt("videoTime");
				String channelId = item.getString("categoryId");
				String channel = "";
				if (channelMap.containsKey(channelId)) {
					channel = channelMap.get(channelId);
				}
				String tags = PageProcessorUtils.unicodeToChinese(item.getString("tag"));
				String summary = PageProcessorUtils.unicodeToChinese(item.getString("desc"));
				long fileSize = item.getLong("videoSize");
				
				int totalCommentCount = 0;
				if (item.containsKey("commentCount")) {
					totalCommentCount = item.getInt("commentCount");
				}
				int totalFavCount = 0;
				if (item.containsKey("favCount")) {
					totalFavCount = item.getInt("favCount");
				}
				//String uploadUserCategoryId = "";
				//if (item.containsKey("userCategoryId")) {
					//uploadUserCategoryId = item.getString("userCategoryId");
				//}
				String uploadUserid = item.getString("userId");
				String uploadDate = DateUtil.convertDateToString(new Date(Long.valueOf(item.getString("uploadTime"))));
				
				//String lastModified = "";
				//if (item.containsKey("lastModified")) {
					//lastModified = item.getString("lastModified");
				//}
				int activity = item.getInt("activity"); 
				int mediaSrc = 0;
				if (item.containsKey("mediaSrc")) {
					mediaSrc = item.getInt("mediaSrc");
				}
				int srcType = item.getInt("srcType");
				int status = item.getInt("status");
				int videoType = item.getInt("videoType");
				int vouch = item.getInt("vouch");
				
				if (activity != 0) {
					log.info("activity="+activity+";playUrl="+playUrl);
				}
				if (mediaSrc != 0) {
					log.info("mediaSrc="+mediaSrc+";playUrl="+playUrl);
				}
				if (videoType != 0&&videoType!=1) {
					log.info("videoType="+videoType+";playUrl="+playUrl);
				}
				if (srcType != 0 && srcType != 1) {
					log.info("srcType="+srcType+";playUrl="+playUrl);
				}
				if (status != 21 && status != -10 && status != -20 && status != 10&& status != -40) {
					log.info("status="+status+";playUrl="+playUrl);
				}
				if (vouch != 0 && vouch != 1) {
					log.info("vouch="+vouch+"videoType="+videoType+";playUrl="+playUrl);
				}
				//srcType=0----表示视频
				//srcType=1----表示图片幻灯片
				//srcType=2----需要安装极速酷6才能放
				//status=21----视频正常
                //status=-10---视频暂时无法访问
				//status=10---视频暂时无法访问
				//status=-20---视频暂时无法访问
				//status=-40---视频暂时无法访问
				//vouch=0 videoType=0--普通视频
				//vouch=1 videoType=1--高清视频
				//vouch=2 videoType=1--清晰视频
				
				String quality = "ad";
				if (vouch == 1 && videoType==1) {
					quality = "hd";
				} else if (vouch == 2 && videoType==1) {
					quality = "cd";
				}

				Ugc ugc = new Ugc();
				ugc.setVideoSite(videoSite);
				ugc.setDomain(domain);
				ugc.setSourceSite(playSite);
				ugc.setPlayUrl(playUrl);
				ugc.setTitle(title);
				ugc.setLogo(logo);
				ugc.setLength(length);
				ugc.setQuality(quality);
				ugc.setChannel(channel);
				ugc.setCategory("");
				ugc.setTags(tags);
				ugc.setSummary(summary);
				ugc.setVid("");
				ugc.setEvid(evid);
				ugc.setOriLogo(logo);
				ugc.setShareUrl(shareUrl);
				//ugc.setTotalPageView(pv);
				ugc.setTotalComment(totalCommentCount);
				ugc.setTotalFav(totalFavCount);
				//ugc.setFileExt(fileExt);
				ugc.setFileSize(fileSize);
				ugc.setUploadUserid(uploadUserid);
				//ugc.setUploadUsername(uploadUsername);	
				//ugc.setUploadUserblog(uploadUserblog);
				ugc.setUploadDate(uploadDate);
				ugc.setLogoStatus("0");
				ugc.setStatus("1");
				ugc.setCrawlUser(crawlUser);
				ugc.setCrawlDate(crawlDate);
				ugc.setUpdateUser(crawlUser);
				ugc.setUpdateDate(crawlDate);

				
				CrawlURI playCrawlURI = new CrawlURI();
				playCrawlURI.setSourceSite(videoSite);
				playCrawlURI.setCrawlUrl(playUrl);
				playCrawlURI.setCharset("utf-8");
				playCrawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_SUCCESS);
				playCrawlURI.setModel(ugc);
				
				if (status != 21) {
					log.info(playUrl+"-数据已经失效,原因:status="+status);
					ugc.setStatus("0");
					playCrawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_INVALID);
				} else if (StringUtils.isEmpty(title) || length==0) {
					log.info(playUrl+"-数据不可用。(title="+title+";length="+length+")");
					ugc.setStatus("0");
					playCrawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_INVALID);
				} else if (srcType != 0) {
					log.info(playUrl+"-UUSEE不可以播放的视频,原因:srcType="+srcType);
					ugc.setStatus("0");
					playCrawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_INVALID);
				}
				
				playCrawlURIList.add(playCrawlURI);
				
				crawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_SUCCESS);
			}
		} catch (Exception e) {
			e.printStackTrace();
			crawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_EXCEPTION);
			throw new RuntimeException("处理用户视频页失败。");
		}
	}
	
	private boolean canProcess(CrawlURI crawlURI) {
		int crawlStatus = crawlURI.getCrawlStatus();
		if (crawlStatus == CrawlStatusCodes.FETCH_SUCCESS) {
			return true;
		} else if (crawlStatus == CrawlStatusCodes.FETCH_SC_NOT_OK) {
			crawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_INVALID);
			return false;
		} else {
			return false;
		}
	}

	public void setChannelMap(Map<String, String> channelMap) {
		this.channelMap = channelMap;
	}
	
	
}
